package com.zscat.mallplus.center.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.zscat.mallplus.center.BaseController;
import com.zscat.mallplus.center.entity.CenterItem;
import com.zscat.mallplus.center.entity.CenterJifen;
import com.zscat.mallplus.center.entity.CenterOrderRecharge;
import com.zscat.mallplus.center.entity.CenterRegisterItem;
import com.zscat.mallplus.center.entity.LiuShui;
import com.zscat.mallplus.center.mapper.CenterOrderRechargeMapper;
import com.zscat.mallplus.center.service.ICenterItemService;
import com.zscat.mallplus.center.service.ICenterJifenService;
import com.zscat.mallplus.center.service.ICenterLevelService;
import com.zscat.mallplus.center.service.ICenterRegisterItemService;
import com.zscat.mallplus.center.utils.StringUtils;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.service.IUmsMemberService;
import com.zscat.mallplus.util.UserUtils;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.UserFaceAuthUtils;
import com.zscat.mallplus.utils.ValidatorUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/center")
public class CenterController extends BaseController {

	@Resource
    private ICenterJifenService centerJifenService;
	@Resource
    private ICenterLevelService centerLevelService;
	@Resource
	private ICenterItemService centerItemService;
	@Resource
	private IUmsMemberService memberService;
    @Resource
    private ICenterRegisterItemService centerRegisterItemService;
	@Resource
	private CenterOrderRechargeMapper centerOrderRechargeMapper;
    
	/**
	 * 身份证认证列表
	 */
    @GetMapping("/list")
    public Object list(CenterJifen centerJifen,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
		try {
			return new CommonResult().success(centerJifenService.page(new Page<CenterJifen>(pageNum, pageSize), new QueryWrapper<>(centerJifen).orderByDesc("real_time")));
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return new CommonResult().failed();
	}
	
	/** 查询用户-积分-余额-等级  */
    @GetMapping(value = "/{userId}")
    public Object getInfo(@PathVariable("userId") Long userId)
    {
    	return new CommonResult().success(this.isCenterJifen(userId));
    }
    
    /** 
     * 消费获得积分
     */
    @GetMapping("update")
    public Object updat(CenterJifen cj)
    {
    	CenterJifen centerJifen = this.isCenterJifen(cj.getUserId());
    	if (cj.getMoney() > 0) {
    		Long score = (long)(cj.getMoney() * 10) + centerJifen.getScore();
			centerJifen.setScore(score);
			Long score2 = centerLevelService.selectCenterLevelById(2L).getScore();//2级所需积分
			Long score3 = centerLevelService.selectCenterLevelById(3L).getScore();//3级所需积分
			if (score > score2) {
				centerJifen.setLevel(2);
			}else if (score > score3) {
				centerJifen.setLevel(3);
			}
			centerJifenService.updateCenterJifen(centerJifen);
	    	CenterItem item = new CenterItem();
	    	item.setUserId(cj.getUserId());
	    	item.setName("消费赠送");
	    	item.setIncome((double)score);
	    	item.setTime(new Date());
	    	item.setType(1);
	    	centerItemService.insertCenterItem(item);
		}
        return this.synchro(cj.getUserId());
    }
    
    /**
     * 签到获得积分
     */
    @GetMapping("register")
    public Object edit(Long userId)
    {
    	CenterJifen centerJifen = this.isCenterJifen(userId);
    	
    	CenterItem item = new CenterItem();
    	item.setUserId(userId);
    	item.setName("每日签到");
    	
    	int regNum = centerJifenService.register(userId);
    	if (regNum == 1) {
			Integer reg = centerJifen.getReg() + 1 ;
			centerJifen.setReg(reg);
			if (reg > 7) {
				centerJifen.setReg(1);
				reg = 1;
			}
			if (reg == 7 ) {
				centerJifen.setScore(centerJifen.getScore() + 10);
				item.setIncome(10.0);
			}else {
				centerJifen.setScore(centerJifen.getScore() + reg);
				item.setIncome((double)reg);
			}
		}else {
			centerJifen.setReg(1);
			centerJifen.setScore(centerJifen.getScore() + 1);
		}
    	item.setTime(new Date());
    	item.setType(1);
    	centerItemService.insertCenterItem(item);
    	centerJifen.setRegTime(new Date());
    	
    	CenterRegisterItem register = new CenterRegisterItem();
    	register.setUserId(userId);
    	register.setNickName(centerJifen.getNickName());
    	register.setPhone(centerJifen.getPhone());
    	register.setTime(new Date());
        if(centerJifenService.updateCenterJifen(centerJifen)>0) {
        	this.synchro(userId);
        	return new CommonResult().success(centerJifenService.selectCenterJifenById(userId));
        }else {
			return new CommonResult().failed();
		}
    }
    /**
     * 初始化积分、余额、等级属性信息
     */
    private CenterJifen isCenterJifen(Long userId) {
    	if (centerJifenService.selectCenterJifenById(userId) == null) {
    		UmsMember member = memberService.getById(userId);
    		CenterJifen centerJifen = new CenterJifen();
    		centerJifen.setUserId(userId);
    		centerJifen.setNickName(member.getNickname()==null? "":member.getNickname());
    		centerJifen.setPhone(member.getPhone()==null? "":member.getPhone());
    		centerJifenService.insertCenterJifen(centerJifen);
		}
    	return centerJifenService.selectCenterJifenById(userId);
	}
    /**
     * 获取会员信息
     */
    private UmsMember getMember(Long userId) {
		return memberService.getById(userId);
	}
    /**
     * 会员信息同步属性表
     */
    private CommonResult synchro(Long userId) {
    	CenterJifen centerJifen = centerJifenService.selectCenterJifenById(userId);
    	UmsMember member = memberService.getById(userId);
    	member.setIntegration(centerJifen.getScore().intValue());
    	member.setBlance(new BigDecimal(centerJifen.getMoney()));
    	member.setMemberLevelId((long)centerJifen.getLevel());
		return toAjax(memberService.updateById(member));
	}
    
    
    /**
     * 实名认证
     */
    @GetMapping("userFace")
    public Object userFace(String base64,String name, String code,Long userId)
    {
    	CenterJifen centerJifen = this.isCenterJifen(userId);
    	boolean face = UserFaceAuthUtils.face(base64, name, code,true);
    	if (face) {
			centerJifen.setIsreal(1);
			centerJifen.setRealName(name);
			centerJifen.setIdNumber(code);
		}
    	centerJifenService.updateCenterJifen(centerJifen);
        return new CommonResult().success(centerJifenService.selectCenterJifenById(userId));
    }
    
    /**
     * 充值积分  余额
     */
    @PutMapping
    public Object edit(@RequestBody CenterJifen centerJifen)
    {
    	CenterJifen jifen = this.isCenterJifen(centerJifen.getUserId());
    	CenterItem item = new CenterItem();
    	item.setUserId(centerJifen.getUserId());
    	if (centerJifen.getMoney() != null || centerJifen.getType() == 2) {
    		item.setType(2);
			if (centerJifen.getMoney() > 0) {
				item.setIncome(centerJifen.getMoney());
				item.setName("余额充值");
			}else if (centerJifen.getMoney() < 0) {
				item.setPay(centerJifen.getMoney());
				item.setName("余额消费");
			}
			jifen.setMoney(centerJifen.getMoney() + jifen.getMoney());
		}else if (centerJifen.getScore() !=null || centerJifen.getType() == 1) {
    		item.setType(1);
			jifen.setScore(centerJifen.getScore() + jifen.getScore());
			if (centerJifen.getScore() > 0) {
				item.setIncome((double)centerJifen.getScore());
				item.setName("积分充值");
			}else if (centerJifen.getScore() < 0) {
				item.setPay((double)centerJifen.getScore());
				item.setName("积分消费");
			}
		}else {
			return new CommonResult().failed();
		}
    	item.setTime(new Date());
    	centerItemService.insertCenterItem(item);
    	return centerJifenService.updateCenterJifen(jifen) > 0 ? 
    			this.synchro(centerJifen.getUserId()):new CommonResult().failed();
        
    }
    
    /**
     * 查询签到明细列表
     */
    @GetMapping("/register/list")
    public Object list(CenterRegisterItem centerRegisterItem)
    {
        List<CenterRegisterItem> list = centerRegisterItemService.selectCenterRegisterItemList(centerRegisterItem);
        return new CommonResult().success(list);
    }
    
    /**
     * 余额充值订单明细
     * @throws ParseException 
     */
    @GetMapping("/balance/list")
    public Object list(CenterOrderRecharge entity,
    		@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) throws ParseException
    {
    	QueryWrapper<CenterOrderRecharge> wrapper = new QueryWrapper<>(entity).orderByDesc("id");
        if (StringUtils.isNotEmpty(entity.getBeginTime()) && StringUtils.isNotEmpty(entity.getEndTime())) {
        	wrapper.between("payment_time", entity.getBeginTime(), entity.getEndTime().replace("00:00:00", "23:59:59"));
        }
        IPage<CenterOrderRecharge> list = centerOrderRechargeMapper.selectPage(new Page<CenterOrderRecharge>(pageNum, pageSize), wrapper);
        return new CommonResult().success(list);
    }
    
    /**
     * 获取邮箱不为空  用户信息
     */
    @GetMapping("/emailNotNull")
    public Object emailNotNull(UmsMember entity,
    		@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize)
    {
        IPage<UmsMember> list = memberService.page(new Page<UmsMember>(pageNum, pageSize), new QueryWrapper<UmsMember>().isNotNull("email"));
        return new CommonResult().success(list);
    }
    
    /**
     * 获取指定用户
     */
    @GetMapping("/getuserByIds")
    public Object getIds(String ids,
    		@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize)
    {
    	QueryWrapper<UmsMember> queryWrapper = new QueryWrapper<UmsMember>();
    	String[] split = ids.split(",");
    	for (String str : split) {
    		queryWrapper.or(i -> i.eq("id", str));
		}
        IPage<UmsMember> list = memberService.page(new Page<UmsMember>(pageNum, pageSize), queryWrapper);
        return new CommonResult().success(list);
    }
    
    /**
     * 流水明细
     */
    @GetMapping("/liushui")
    public Object getLiushui(LiuShui liushui,
    		@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
    	List<LiuShui> page = new ArrayList<LiuShui>();
    	Integer storeId = UserUtils.getCurrentMember().getStoreId();
    	PageHelper.startPage(pageNum, pageSize);
    	
    	if (storeId !=null && storeId > 0) {
    		page = centerJifenService.liushuiOrderList(liushui);
		}else {
			page = centerJifenService.liushuiList(liushui);
		}
    	return new CommonResult().success(page);
    }
}
